 <template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <text class="title">智慧运维云系统</text>
    </view>
    <view class="login-form-content">
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input v-model="loginForm.username" class="input" type="text" placeholder="请输入手机号" maxlength="11" />
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
      </view>
      <view class="input-item flex align-center" v-if="captchaEnabled">
        <view class="iconfont icon-code icon"></view>
        <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
        <image :src="codeUrl" @click="getCode" class="login-code-img"></image>
      </view>
	<!--  <view class="remember-psw">
	  		<uni-data-checkbox multiple selectedColor="#0081FF" selectedTextColor="grey" v-model="rememberPsw" :localdata="range" @change="checkboxChange">记住账号密码</uni-data-checkbox>
	  </view> -->
      <view class="action-btn" >
        <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button>
      </view>
	  <!-- 记住密码功能 -->
	  
    </view>

    <view class="xieyi text-center">
		
      <text class="text-grey1">没有账号？</text>
      <text @click="handleReg" class="text-blue">立即注册</text>
    </view> 

  </view>
  
</template>

<script>
  import { getCodeImg } from '@/api/login'
  import { getOpenid } from '@/api/register.js';

  export default {
    data() {
      return {
        codeUrl: "",
        captchaEnabled: false,
		rememberPsw: [1],//复选框状态 默认勾选
        globalConfig: getApp().globalData.config,
		range: [{"value": 1,"text": "记住账号密码"	}],
        loginForm: {
          username: "",
          password: "",
          code: "",
          uuid: '',
		  openid: "",
		  sessionKey: ""
        }
      }
    },
	mounted() {
		//记住密码
		//缓存的账号
		const HBusername = uni.getStorageSync('HBusername');
		//缓存的密码
		const HBpassword = uni.getStorageSync('HBpassword');
		// const rememberPsw = uni.getStorageSync('rememberPsw');
		console.log("缓存的账号:", HBusername)
		console.log("缓存的密码:", HBpassword)
		// console.log("缓存的选中状态:", rememberPsw)
		//有缓存就赋值给文本没有就清空
		if (HBusername && HBpassword) {
			this.loginForm.username = HBusername;
			this.loginForm.password = HBpassword;
		} else {
			this.loginForm.username = '';
			this.loginForm.password = '';
		}
		// this.rememberPsw = rememberPsw;
		//自动登录
	},
    created() {
      this.getCode()
    },
    methods: {
		//复选框
		checkboxChange: function(e) {
			// console.log("复选框状态:", e);
			console.log("复选框状态:", e.detail.value.length);
			console.log("复选框状态:rememberPsw", this.rememberPsw);
			// uni.getStorageSync('rememberPsw', this.rememberPsw.length);
			if (e.detail.value.length === 1) {
				//获取缓存的账号 赋值
				uni.getStorageSync('HBusername',this.loginForm.username);
				uni.getStorageSync('HBpassword',this.loginForm.password);
			} else {//销毁
				uni.removeStorageSync('HBusername');
				uni.removeStorageSync('HBpassword');
			}
		},
		handle(){
			uni.makePhoneCall({
				phoneNumber: '114' //仅为示例
			});
		},
		handleReg(){
			this.$tab.navigateTo(`/pages/work/register/index`)
		},
		// 隐私协议
		handlePrivacy() {
			let site = this.globalConfig.appInfo.agreements[0]
			this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
		},
		// 用户协议
		handleUserAgrement() {
			let site = this.globalConfig.appInfo.agreements[1]
			this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
		},
		// 获取图形验证码
		getCode() {
			getCodeImg().then(res => {
				this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
				if (this.captchaEnabled) {
					this.codeUrl = 'data:image/gif;base64,' + res.img
					this.loginForm.uuid = res.uuid
				}
			})
		},
		// 获取小程序用户openid
		getUserInfo(){
			const _this = this;
			uni.login({
				provider: 'weixin',
				success: function (loginRes) {
					// console.log('AAAAAAAAAAAA');
					// console.log('toLogin==========11111', loginRes);
					// console.log('toLogin==========22222', loginRes.errMsg);
					//self.code = loginRes.code;
					// self.loginEvent(loginRes.code, fn); 
					//用code去创建用户信息，或者查询用户的基本信息
					if(loginRes.errMsg === "login:ok"){
						getOpenid(loginRes.code).then(res => {
							console.log('BBBBBBB');
							console.log('getOpenid==========11111', res);
							if(res.code === 200){
								_this.loginForm.sessionKey = res.data.sessionKey
								_this.loginForm.openid = res.data.openid
							}
							// console.log('CCCCCCCC4========11111', loginRes);
							_this.pwdLogin()
						})
					}else{
						_this.pwdLogin()
					}
				
					// uni.getUserInfo({
					//     provider: 'weixin',
					//     success: function (infoRes) {
					//         console.log(':::::：' + infoRes);
							
					//     },
					//     fail: function () {
					//         console.log('3333333333');
					//     },
					//     complete: function () {
					//         console.log('44444444444444');
					//     }
					// });
				}
			});
		},
		// 登录方法
		async handleLogin() {
			if (this.loginForm.username === "") {
				this.$modal.msgError("请输入您的手机号")
			} else if (this.loginForm.password === "") {
				this.$modal.msgError("请输入您的密码")
			} else if (this.loginForm.code === "" && this.captchaEnabled) {
				this.$modal.msgError("请输入验证码")
			} else {
				this.$modal.loading("登录中，请耐心等待...")
				// 登录时先获取openid，登录过程同步绑定用户openid
				this.getUserInfo()
				// this.pwdLogin()
			}
		},
		// 密码登录
		async pwdLogin() {
			this.$store.dispatch('Login', this.loginForm).then(() => {
				//勾选就缓存账号和密码
				// console.log('rememberPsw', this.rememberPsw.length)
				if (this.rememberPsw.length) {
					uni.setStorageSync('HBusername', this.loginForm.username);
					uni.setStorageSync('HBpassword', this.loginForm.password);
				} else {//销毁缓存
					uni.removeStorageSync('HBusername');
					uni.removeStorageSync('HBpassword');
				}
				this.$modal.closeLoading()
				this.loginSuccess()
			}).catch(() => {
				if (this.captchaEnabled) {
					this.getCode()
				}
			})
		},
		// 登录成功后，处理函数
		loginSuccess(result) {
			// 设置用户信息
			this.$store.dispatch('GetInfo').then(res => {
				this.$tab.reLaunch('/pages/work/index')
			})
		},
		openService(){
			console.log("open success!");
		}
    }
  }
</script>

<style lang="scss">
  page {
    background-color: #ffffff;
  }

  .normal-login-container {
    width: 100%;

    .logo-content {
      width: 100%;
      font-size: 21px;
      text-align: center;
      padding-top: 15%;

      image {
        border-radius: 4px;
      }

      .title {
        margin-left: 5px;
      }
    }

    .login-form-content {
      text-align: center;
      margin: 20px auto;
      margin-top: 15%;
      width: 80%;

      .input-item {
        margin: 20px auto;
        background-color: #f5f6f7;
        height: 45px;
        border-radius: 20px;

        .icon {
          font-size: 38rpx;
          margin-left: 10px;
          color: #999;
        }

        .input {
          width: 100%;
          font-size: 14px;
          line-height: 20px;
          text-align: left;
          padding-left: 15px;
        }

      }

      .login-btn {
        margin-top: 10px;
        height: 45px;
      }

      .xieyi {
        color: #333;
        margin-top: 20px;
      }
	  
	  .remember-psw {
	    text-align: left;
	  }
    }

    .easyinput {
       width: 100%;
    }
  }

  .login-code-img {
    height: 45px;
  }
  
</style>
